# Create your views here.
from django.http import HttpResponse
from django.template import RequestContext, loader
from forms import *
from django.shortcuts import render, redirect
from models import *

def login(request):
    if request.method == 'POST':
        f = loginForm(request.POST)
        if(f.is_valid()):
            # TODO insert code here to do Login Validation
            userEmail = f.cleaned_data['Email']
            graderList = Grader.objects.filter(Email=userEmail)
            if(graderList.count()!=0):
                request.session['user_id'] = graderList[0].id
                return redirect('/')
            return HttpResponse('Sorry! Try again!  Not Found: ' + f.cleaned_data['Email'] + '!')
    else:
        sessionUser = request.session.get('user_id', 'none')
        if(sessionUser!='none'):
            # Means someone is already logged in!
            userObj = Grader.objects.get(pk=sessionUser)
            return redirect('/home')
            #return HttpResponse('You are already logged in ' + userObj.Name + '! Go to http://127.0.0.1/logout to log yourself out!')
        f = loginForm()
        
    #t = loader.get_template('fetchemApp/login.html')
    #c = RequestContext(request, {'hello': 'Hi!'})
    return render(request, 'fetchemApp/login.html', {'loginForm': f})

def home(request):
    sessionUser = request.session.get('user_id', 'none')
    if(sessionUser!='none'):
        userObj = Grader.objects.get(pk=sessionUser)
        courses = []
        for c in userObj.course_set.all():
            courses.append(c.Name)
        t = loader.get_template('fetchemApp/home.html')
        c = RequestContext(request, {'hello': 'Hi!', 'Name': userObj.Name, 'Courses': courses})
        return HttpResponse(t.render(c))
    else:
        return redirect('/')

def logout(request):
    try:
        del request.session['user_id']
    except KeyError:
        pass
    return redirect('/')
